<template>
  <div>
    <el-card class="form-container">
      <el-form
          ref="productForm"
          :model="productForm"
          :rules="formRules"
          label-position="left"
          label-width="100px"
          style="width: 800px; 
          margin-left: 100px">
        <el-form-item label="商品分类" prop="category">
          <el-cascader
            :props="defaultParams"
            v-model="selectOptions"
            :options="categoryOptions"></el-cascader>
        </el-form-item>
        
        <el-form-item label="商品名称"  prop="name">
            <el-input v-model="productForm.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="商品副标题"  prop="subTitle">
            <el-input v-model="productForm.subTitle" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="商品品牌" prop="brandId">
          <el-select v-model="productForm.brandId" placeholder="请选择">
            <el-option
              v-for="item in brandOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="商品售价" prop="price">
          <el-input v-model="productForm.price" />

        </el-form-item>
        <el-form-item label="商品排序">
          <el-input v-model="productForm.sort" />
        </el-form-item>
        <el-form-item label="商品主图">
          <template slot-scope="">

          </template>
          <el-upload
            class="uploader"
            :action="uploadUrl + '/file/upload'"
            :show-file-list="false"
            :on-success="handlePictureSuccess"
            >
            <img v-if="productForm.coverImg" :src="productForm.coverImg" width="100%">
            <i v-else class="el-icon-plus uploader-icon"></i>
              <!-- <i slot="default" class="el-icon-plus"></i> -->
              <!-- <div slot="file" slot-scope="{file}">
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url" alt=""
                >
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleDownload(file)"
                  >
                    <i class="el-icon-download"></i>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div> -->
          </el-upload>
          <!-- <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog> -->
        </el-form-item>
        <el-form-item label="商品详情">
          <el-upload
            multiple
            :show-upload-list="false"
            :format="['jpg','jpeg','png','gif']"
            class="quill-upload"
            :on-success="quillSuccess"
            :action="uploadUrl + '/file/upload'"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <quill-editor 
            v-model="productForm.detailHtml"
            :options="editorOption"
            ref="myQuillEditor">
          </quill-editor>

        </el-form-item>
        <el-form-item style="margin-left: 80px;">
          <el-button style="margin-top: 12px" @click="submitproductForm('productForm')" type="primary">保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
  
</template>

<script>

import { getCategoryList } from '@/api/category'
import { geBrandtList } from '@/api/brand'
import { saveProduct, getProductInfo } from '@/api/product'
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // toggled buttons
  ['blockquote', 'code-block'],

  [{ header: 1 }, { header: 2 }], // custom button values
  [{ list: 'ordered' }, { list: 'bullet' }],
  [{ script: 'sub' }, { script: 'super' }], // superscript/subscript
  [{ indent: '-1' }, { indent: '+1' }], // outdent/indent
  [{ direction: 'rtl' }], // text direction

  [{ size: ['small', false, 'large', 'huge'] }], // custom dropdown
  [{ header: [1, 2, 3, 4, 5, 6, false] }],

  [{ color: [] }, { background: [] }], // dropdown with defaults from theme
  [{ font: [] }],
  [{ align: [] }],
  ['link', 'image'],
  ['clean'] // remove formatting button
]

export default {
  name: 'addProduct',
  data() {
    return {
      id: this.$route.query.id ? this.$route.query.id : null,
      uploadUrl: process.env.VUE_APP_BASE_API,
      productForm: { price: 0,sort: 0, },
      defaultParams: {
        label: 'name',
        value: 'id',
        children: 'children'
      },
      categoryOptions: [],
      brandOptions: [],
      selectOptions: [],
      editor: null,
      html: '<p>hello</p>',
      toolbarConfig: { },
      editorConfig: { placeholder: '请输入内容...' },
      mode: 'default',
      formRules: {
        categoryOptions: [
          { required: true, message: '请选择商品分类', trigger: 'change' },
        ],
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        subTitle: [
          { required: true, message: '请输入商品副标题', trigger: 'blur' },
        ],
        brandId: [
          { required: true, message: '请选择商品品牌', trigger: 'change' },
        ],
        price: [
          { required: true, message: '请输入商品售价', trigger: 'blur' },
        ],
      },
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions,
            handlers: {
              // 重写点击组件上的图片按钮要执行的代码
              'image': function (value) {
                document.querySelector('.quill-upload .el-icon-upload').click()
              }
            }
          }
        }
      },

    }
  },
  created() {
    this.onLoad()
  },
  methods: {
    onLoad() {
      getCategoryList().then(res => {
        if(res.code === 200) {
          this.categoryOptions = res.data;
        }
      })
      geBrandtList().then(res => {
        if(res.code === 200) {
          this.brandOptions = res.data;
        }
      })
      if(this.id != null) {
        getProductInfo(this.id).then(res => {
          if(res.code === 200) {
            
            this.productForm = res.data;
            this.selectOptions[0] = this.productForm.cid1;
            this.selectOptions[1] = this.productForm.cid2;
            console.log(this.productForm ,this.selectOptions);
          }
        })
      }
      
    },
    handleRemove(file) {
        console.log(file);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    handlePictureSuccess(res) {
      if(res.code === 200) {
        this.productForm.coverImg = res.data
      }
    },
    quillSuccess(res) {
      if(res){
      // 获取文本编辑器
      const quill=this.$refs.myQuillEditor.quill
      // 获取光标位置
      const pos=quill.getSelection().index
      // 插入图片到光标位置
      quill.insertEmbed(pos,'image',res.data)
      }else{
        this.$essage.error('图片插入失败')
      }
    },
    submitproductForm(productForm) {
      this.$refs[productForm].validate(valid => {
        if(valid) {
          this.productForm.cid1 = this.selectOptions[0]
          this.productForm.cid2 = this.selectOptions[1]
          saveProduct(this.productForm).then(res => {
            if(res.code === 200){
              this.productForm = {
                price: 0,
                sort: 0,
              }
              this.$router.go(0)
              this.$message.success("提交成功")
            }
          })
        }
      }) 
      
    }
  }

}
</script>

<style lang="scss">
  .form-container {
    
    // position: absolute;
    left: 0;
    right: 0;
    width: 1200px;
    padding: 35px 35px 15px;
    margin: 20px auto;
  }
  .uploader{
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .el-upload:hover {
      border-color: #409EFF;
    }
    .uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
  }
  
</style>